class Release < ActiveRecord::Base
  #Relations
  has_and_belongs_to_many :artists
  belongs_to	:forum, :dependent => :destroy
  has_many	:images, :as => :photographable, :dependent => :destroy
  has_many	:editions, :dependent => :destroy
  has_many	:reviews, :as => :reviewable, :dependent => :destroy
  has_many	:edits, :as => :editable, :order => "created_at DESC"
  
  accepts_nested_attributes_for :editions

  #
  attr_accessor :artist_id
  attr_accessor :status

  #Callbacks
  after_update :create_edit 
  after_create :new_entry_edit
  before_save  :add_forum
  after_create :link_artist
  after_create :create_edition

  #Constants
  RELEASE_TYPES = Array.new(['Studio', 'EP', 'Single', 'Live Recording', 'Mixtape', 'Remix', 'Album', 'Bootleg', 'Unrelease', 'Unknown'])
  
  #
  #
  def to_s
    return title
  end

  #
  def to_param
    "#{id}-#{title.parameterize}"
  end

  def primary_image
    if images.empty?
      return nil
    else
      images.first.image
    end
  end

  #
  #
  def get_edition(edition_id)
    if edition_id
      return Edition.find(edition_id.to_i)
    else
      return self.editions.first
    end
  end

  private

  #
  #
  def add_forum
    if self.new_record?
      title = self.title + " Forum"
      forum = Forum.new(:title => title)
      forum.save!
      self.forum_id = forum.id
    end
  end  

  #
  #
  def new_entry_edit
    entry = Hash.new
    entry.store("created", [self.title])
    Edit.create_edit(entry, self)
  end

  #
  #
  def create_edit
    if self.changed?
      Edit.create_edit(self.changes, self)
    end
  end

  #
  #
  def link_artist
    if @artist_id
      artist = Artist.find(@artist_id)
      self.artists << artist
    end
  end

  #
  #
  def create_edition
    if @status
      edition = Edition.new
      edition.title = self.title
      edition.release_id = self.id
      edition.status = @status

      edition.save!
    end
  end
end
